import React, { useEffect, useState } from 'react'
import {Menu} from "antd"
import {items2} from "../config/menus"
import {useNavigate} from "react-router-dom"
import {useDispatch} from "react-redux"
import {addMenu} from "../store/features/checkMenuReducer"

export default function MyMenu() {
    const navigate = useNavigate()
    const [userInfo,setUserInfo] = useState()
    const dispatch = useDispatch()

    const checkedMenu = ({ item, key, keyPath, domEvent })=>{
        console.log(key);
        //路由跳转  this.$router.push() $router.replace()
        // navigate(key)
        console.log(item);
        const label = domEvent.target.innerText;

        const element = {
            key,
            label,
            status:true
        }

        dispatch(addMenu(element))

    }
    useEffect(()=>{
        const info = JSON.parse(localStorage.userInfo || "{}")
        setUserInfo(info)
    },[])

    /**
     * 进行菜单的筛选，筛选完成后返回指定菜单，并页面渲染
     * @returns 
     * // userInfo如果undefine或者null 结束往后继续执行
        // ?.   if(userInfo && userInfo.role && userInfo.role.menus){}
        // userInfo.role = {menus:[]}
        //登录成功后，获取当前这个用户能访问的菜单
     */
    const createMenu = (array,news = [])=>{
        const userMenus = userInfo?.role?.menus || []
        //userMenus = ["/home/user","/home/role"]
        //menus.js = [{key:"/home/user",title="",children:[]}]
        for (const menu of array) {
            //用我能访问的菜单和所有菜单对比。匹配成功就留下。匹配失败过滤
            if(!menu.children){
                if(userMenus.includes(menu.key)){
                    news.push(menu)
                }
            }else{
                let node = {...menu,children:[]}
                createMenu(menu.children,node.children)
                if(node.children.length !=0){
                    news.push(node)
                }
            }
        }
        return news
    }
    return (
        <Menu
            onClick={checkedMenu}
            mode="inline"
            defaultSelectedKeys={['/home/']}
            defaultOpenKeys={['/home/product', "/home/charts"]}
            style={{
                height: '100%',
                borderRight: 0,
            }}
            items={createMenu(items2)}
        />
    )
}
